import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/extension/ex_widget.dart';
import 'package:flutter_massage/common_lib/http/index.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/common_lib/ui/common_component.dart';
import 'package:flutter_massage/generated/assets.dart';
import 'package:flutter_massage/pages/my/my_logic.dart';
import 'package:flutter_massage/pages/my/setting/setting_logic.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/values/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class ApiLogout extends CommonApi {
  ApiLogout(String key) : super('sign/?a=index', {'key': key});
}

class SettingPage extends GetView<SettingLogic> {
  const SettingPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      resizeToAvoidBottomInset: false,
      titleStr: '设置',
      child: GetBuilder<SettingLogic>(
        init: SettingLogic(),
        assignId: true,
        builder: (logic) {
          final double w = 55.w;
          String avatar = XydUserService.avatar;
          Widget avatarWidget = Container();
          bool exist = File(avatar).existsSync();
          if (exist) {
            avatarWidget = Image.file(File(avatar), fit: BoxFit.cover, width: w, height: w);
          } else {
            avatarWidget = Assets.svgMyIconPlaceholder.toSvg(width: w, height: w);
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildItem(
                '头像',
                ClipRRect(
                  borderRadius: BorderRadius.circular(w),
                  child: avatarWidget,
                ),
                onTap: () {
                  ActionBottomSheet.actionSheet(
                    items: [
                      ActionSheetConfig(
                        text: '拍照',
                        onTap: () async {
                          AssetEntity? assetEntity = await ActionPicker.camera();
                          if (assetEntity != null) {
                            File? file = await assetEntity.file;
                            if (file != null) XydUserService.editAvatar(file.path);
                            logic.update();
                            CommonObservable().publishChange(MyLogic.keyListener);
                          }
                        },
                      ),
                      ActionSheetConfig(
                        text: '从相册选择',
                        onTap: () async {
                          List<AssetEntity>? images = await ActionPicker.assets(maxAssets: 1);
                          if (images != null && images.isNotEmpty) {
                            AssetEntity assetEntity = images.first;
                            File? file = await assetEntity.file;
                            if (file != null) XydUserService.editAvatar(file.path);
                            logic.update();
                            CommonObservable().publishChange(MyLogic.keyListener);
                          }
                        },
                      ),
                    ],
                  );
                },
              ),
              CommonDivider(marginLeft: 16.w, marginRight: 16.w),
              _buildItem(
                '昵称',
                TextWidget.oneLine(
                  text: XydUserService.nickName,
                  fontSize: 15,
                  color: AppColors.textLevelOne,
                ),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.w),
                onTap: () {
                  SmartDialog.show(
                    builder: (context) => ChangeNameComponent(logic),
                    backDismiss: true,
                    clickMaskDismiss: true,
                    tag: ChangeNameComponent.tag,
                  );
                },
              ),
              const Spacer(),
              _buildLogOff(),
              const CommonDivider(),
              _buildLogout(),
              CommonMargin.height(ScreenUtil().bottomBarHeight * 0.5),
            ],
          );
        },
      ),
    );
  }

  Widget _buildLogOff() {
    return ButtonWidget.text(
      '注销账号',
      alignment: Alignment.center,
      height: 50.w,
      hasInkWell: false,
      textColor: AppColors.textLevelOne,
      fontSize: 16,
      fontWeight: FontWeight.bold,
      onTap: () async {
        Loading.show();
        String title = '您真的要注销账号吗？';
        dynamic json = await CommonNet.get(ApiSetting.logOffTitle());
        if (json != null && json['data'] != null && json['data']['tip'] != null) {
          title = json['data']['tip'];
        }
        await Loading.dismiss();
        CommonDialog.cupertinoTwoButton(
          title: title.replaceAll('\\n', '\n'),
          cancelTitle: '不了',
          confirmTitle: '注销',
          onConfirm: () async {
            Loading.show();
            dynamic json = await CommonNet.post(ApiSetting.logOff());
            if (json != null && json['code'] == 200) {
              await Loading.dismiss();
              Loading.toast('注销失败');
              CommonRoute.openLogin();
            } else {
              await Loading.dismiss();
              Loading.toast('注销失败');
            }
          },
        );
      },
    );
  }

  Widget _buildLogout() {
    return ButtonWidget.text(
      '退出登录',
      alignment: Alignment.center,
      height: 50.w,
      hasInkWell: false,
      textColor: '#FF5147'.toColor,
      fontSize: 16,
      fontWeight: FontWeight.bold,
      onTap: () {
        CommonDialog.cupertinoTwoButton(
          title: '您真的要退出登录吗？',
          cancelTitle: '不了',
          confirmTitle: '退出登录',
          onConfirm: () async {
            Loading.show();
            await CommonNet.post(ApiLogout(XydUserService.key));
            XydUserService.loginOut();
            Loading.dismiss();
            CommonRoute.openLogin();
          },
        );
      },
    );
  }

  Widget _buildItem(String title, Widget content, {EdgeInsets? padding, VoidCallback? onTap}) {
    return Padding(
      padding: padding ?? EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
      child: ButtonWidget(
        onTap: onTap,
        hasInkWell: false,
        child: Row(
          children: [
            TextWidget.oneLine(text: title, fontSize: 15, color: AppColors.textLevelOne),
            const Spacer(),
            content,
            Assets.svgArrowRightGray.toSvg(width: 10.w, color: AppColors.textLevelTwo).paddingLeft(12.w),
          ],
        ),
      ),
    );
  }
}

class ChangeNameComponent extends StatelessWidget {
  const ChangeNameComponent(this.logic, {super.key});

  static const String tag = 'ChangeNameComponent';

  final SettingLogic logic;

  @override
  Widget build(BuildContext context) {
    logic.focusNode.requestFocus();
    logic.textEditingController.text = XydUserService.nickName;
    return Container(
      width: 300.w,
      decoration: CommonDecoration.getShapeDecoration(bg: Colors.white, radius: 12.w),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ButtonWidget.icon(
            Assets.svgDialogClose.toSvg(width: 12.w),
            padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 16.w),
            onTap: () => SmartDialog.dismiss(tag: tag),
            hasInkWell: false,
          ).alignRight(),
          const TextWidget.oneLine(
            text: '修改昵称',
            fontSize: 19,
            color: AppColors.textLevelOne,
            fontWeight: FontWeight.bold,
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(4.w),
            child: TextField(
              decoration: const InputDecoration(
                border: InputBorder.none,
                hintText: '请输入昵称',
                hintStyle: TextStyle(fontSize: 16, color: AppColors.textLevelThree),
                fillColor: AppColors.grayF8,
                filled: true,
              ),
              cursorColor: AppColors.primaryGreen,
              controller: logic.textEditingController,
              focusNode: logic.focusNode,
              style: const TextStyle(fontSize: 16),
            ),
          ).padding(all: 20.w),
          ButtonWidget.text(
            '保存',
            width: 150.w,
            height: 38.w,
            alignment: Alignment.center,
            borderRadius: 8.w,
            gradient: CommonDecoration.xydGradient,
            textColor: Colors.white,
            fontSize: 14,
            onTap: () async {
              if (logic.textEditingController.text.empty) return;
              await XydUserService.editName(logic.textEditingController.text);
              logic.update();
              CommonObservable().publishChange(MyLogic.keyListener);
              SmartDialog.dismiss(tag: tag);
            },
            hasInkWell: false,
          ).paddingBottom(20.w),
        ],
      ),
    );
  }
}
